package org.cllib.geometry;

public class Polygon {
	int[] points;
	
	public Polygon(int[] points){
		if(points.length % 2 != 0){
			throw new IllegalArgumentException("number of coordinates should be even passed[" + points.length + "]");
		}
		
		if(points.length < 6){
			throw new IllegalArgumentException("minimum number 8 passed [" + points.length + "]");
		}
		
		this.points = new int[points.length];
		System.arraycopy(points, 0, this.points, 0, points.length);
	}
	
	public boolean isConvex(){
		boolean initialized = false;
		int f = 0;
		
		for (int i = 0; i < points.length ; i+= 2) {
			final int x1 = points[i];
			final int y1 = points[i + 1];
			
			final int ni = (i + 2) % points.length;
			
			final int x2 = points[ni];
			final int y2 = points[ni + 1];
			
			for (int j = 0; j < points.length; j += 2) {
				if(j != i && j != ni){
					int _f = GeometryUtil.fxy(x1, y1, x2, y2, points[j], points[j + 1]);
					
					if(_f > 0){
						_f = 1;
					}else if(f == 0){
						_f = 0;
					}else{
						_f = -1;
					}
					
					if(!initialized){
						f = _f;
						initialized = true;
					}else{
						if(f != _f){
							return false;							
						}
					}
				}
			}
		}
		return true;
	}
	
	public int[] getPoints(){
		return points;
	}
	
}
